﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessLogic;
using System.Web.Security;

namespace SEP.Admin
{
    public partial class CodeTableManagement : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {       
            if(!IsPostBack)
            {
                BindInfo();
            }
        }

        private void BindInfo()
        {
            Common.Utility.BindCodeTableToGridView<AddressType>(grvAddresses);
            Common.Utility.BindCodeTableToGridView<EmailType>(grvEmailAddresses);
            Common.Utility.BindCodeTableToGridView<PhoneType>(grvPhones);
            Common.Utility.BindCodeTableToGridView<RelationshipType>(grvRelationships);
            Common.Utility.BindCodeTableToGridView<InstrumentType>(grvInstruments);
            Common.Utility.BindCodeTableToGridView<ManufacturerType>(grvManufacturers);
        }
        
        #region Phone types
        protected void lnkAddPhone_Click(object sender, EventArgs e)
        {
            AddCodeTable<PhoneType>(txtDescriptionPhone);
        }

        protected void grvPhones_CancelRecord(object sender, GridViewCancelEditEventArgs e)
        {
            SetIndex(grvPhones, -1);
        }

        protected void grvPhones_EditRecord(object sender, GridViewEditEventArgs e)
        {
            SetIndex(grvPhones, e.NewEditIndex);
        }

        protected void grvPhones_UpdateRecord(object sender, GridViewUpdateEventArgs e)
        {
            UpdateCodeTable<PhoneType>(grvPhones, e.RowIndex);
        }

        protected void grvPhones_DeleteRecord(object sender, GridViewDeleteEventArgs e)
        {
            DeleteCodeTable<PhoneType>(new Guid(grvPhones.DataKeys[e.RowIndex].Value.ToString()));
        }

        protected void grvPhones_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            RowDataBound(e, "phone type");
        }
        #endregion

        #region Address types
        protected void lnkAddAddress_Click(object sender, EventArgs e)
        {
            AddCodeTable<AddressType>(txtDescriptionAddress);
        }

        protected void grvAddresses_CancelRecord(object sender, GridViewCancelEditEventArgs e)
        {
            SetIndex(grvAddresses, -1);
        }

        protected void grvAddresses_EditRecord(object sender, GridViewEditEventArgs e)
        {
            SetIndex(grvAddresses, e.NewEditIndex);
        }

        protected void grvAddresses_UpdateRecord(object sender, GridViewUpdateEventArgs e)
        {
            UpdateCodeTable<AddressType>(grvAddresses, e.RowIndex);
        }

        protected void grvAddresses_DeleteRecord(object sender, GridViewDeleteEventArgs e)
        {
            DeleteCodeTable<AddressType>(new Guid(grvAddresses.DataKeys[e.RowIndex].Value.ToString()));
        }

        protected void grvAddresses_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            RowDataBound(e, "address type");
        }
        #endregion

        #region Email types
        protected void lnkAddEmail_Click(object sender, EventArgs e)
        {
            AddCodeTable<EmailType>(txtDescriptionEmail);
        }

        protected void grvEmailAddresses_CancelRecord(object sender, GridViewCancelEditEventArgs e)
        {
            SetIndex(grvEmailAddresses, -1);
        }

        protected void grvEmailAddresses_EditRecord(object sender, GridViewEditEventArgs e)
        {
            SetIndex(grvEmailAddresses, e.NewEditIndex);
        }

        protected void grvEmailAddresses_UpdateRecord(object sender, GridViewUpdateEventArgs e)
        {
            UpdateCodeTable<EmailType>(grvEmailAddresses, e.RowIndex);
        }

        protected void grvEmailAddresses_DeleteRecord(object sender, GridViewDeleteEventArgs e)
        {
            DeleteCodeTable<EmailType>(new Guid(grvEmailAddresses.DataKeys[e.RowIndex].Value.ToString()));
        }

        protected void grvEmailAddresses_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            RowDataBound(e, "email address type");
        }
        #endregion

        #region Relationships
        protected void lnkAddRelationship_Click(object sender, EventArgs e)
        {            
            AddCodeTable<RelationshipType>(txtDescriptionRelationship);
        }

        protected void grvRelationships_CancelRecord(object sender, GridViewCancelEditEventArgs e)
        {
            SetIndex(grvRelationships, -1);
        }

        protected void grvRelationships_EditRecord(object sender, GridViewEditEventArgs e)
        {
            SetIndex(grvRelationships, e.NewEditIndex);
        }

        protected void grvRelationships_UpdateRecord(object sender, GridViewUpdateEventArgs e)
        {
            UpdateCodeTable<RelationshipType>(grvRelationships, e.RowIndex);
        }

        protected void grvRelationships_DeleteRecord(object sender, GridViewDeleteEventArgs e)
        {
            DeleteCodeTable<RelationshipType>(new Guid(grvRelationships.DataKeys[e.RowIndex].Value.ToString()));
        }

        protected void grvRelationships_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            RowDataBound(e, "relationship type");
        }
        #endregion

        #region Instrument types
        protected void lnkAddInstruments_Click(object sender, EventArgs e)
        {
            AddCodeTable<InstrumentType>(txtDescriptionInstruments);
        }

        protected void grvInstruments_CancelRecord(object sender, GridViewCancelEditEventArgs e)
        {
            SetIndex(grvInstruments, -1);
        }

        protected void grvInstruments_EditRecord(object sender, GridViewEditEventArgs e)
        {
            SetIndex(grvInstruments, e.NewEditIndex);            
        }

        protected void grvInstruments_UpdateRecord(object sender, GridViewUpdateEventArgs e)
        {
            UpdateCodeTable<InstrumentType>(grvInstruments, e.RowIndex);
        }

        protected void grvInstruments_DeleteRecord(object sender, GridViewDeleteEventArgs e)
        {
            DeleteCodeTable<InstrumentType>(new Guid(grvInstruments.DataKeys[e.RowIndex].Value.ToString()));
        }

        protected void grvInstruments_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            RowDataBound(e, "instrument type");
        }
        #endregion

        #region Manufacturers
        protected void lnkAddManufacturers_Click(object sender, EventArgs e)
        {
            AddCodeTable<ManufacturerType>(txtDescriptionManufacturers);
        }

        protected void grvManufacturers_CancelRecord(object sender, GridViewCancelEditEventArgs e)
        {
            SetIndex(grvManufacturers, -1);
        }

        protected void grvManufacturers_EditRecord(object sender, GridViewEditEventArgs e)
        {
            SetIndex(grvManufacturers, e.NewEditIndex);
        }

        protected void grvManufacturers_UpdateRecord(object sender, GridViewUpdateEventArgs e)
        {
            UpdateCodeTable<ManufacturerType>(grvManufacturers, e.RowIndex);
        }

        protected void grvManufacturers_DeleteRecord(object sender, GridViewDeleteEventArgs e)
        {
            DeleteCodeTable<ManufacturerType>(new Guid(grvManufacturers.DataKeys[e.RowIndex].Value.ToString()));
        }

        protected void grvManufacturers_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            RowDataBound(e, "manufacturer");
        }
        #endregion

        #region Helper methods
        private void AddCodeTable<T>(TextBox textbox) where T : CodeTable<T>, new()
        {
            string description = textbox.Text;
            string msg = "Record successfully added.";

            if (!string.IsNullOrWhiteSpace(description))
            {                
                try
                {
                    T t = new T();
                    t.Description = description;
                    t.Create();
                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                }
            }
            else
            {
                msg = "You must enter a description.";
            }

            lblMessage.Text = msg;
            textbox.Text = string.Empty;
            
            BindInfo();
        }

        private bool DeleteCodeTable<T>(Guid id) where T : CodeTable<T>, new()
        {
            bool result = false;
            string msg = "Record successfully deleted.";

            if(id != Guid.Empty)
            {
                try
                {
                    T t = new T();
                    t.ID = id;
                    t.Delete();   
                    result = true;                 
                }
                catch (Exception ex)
                {                    
                    msg = ex.Message;
                }
            }

            lblMessage.Text = msg;
            
            if(result)
            {
                BindInfo();
            }

            return result;
        }

        private bool UpdateCodeTable<T>(GridView grv, int rowIndex) where T : CodeTable<T>, new()
        {
            Guid id = new Guid(grv.DataKeys[rowIndex].Value.ToString());

            GridViewRow row = grv.Rows[rowIndex];
            TextBox txtgDescription = (TextBox)row.FindControl("txtDescription");
            string description = txtgDescription.Text;
            bool result = false;
            string msg = "Record successfully updated.";

            if (!string.IsNullOrWhiteSpace(description))
            {
                if (!string.IsNullOrWhiteSpace(description) && id != Guid.Empty)
                {
                    try
                    {
                        T t = new T();
                        t.ID = id;
                        t.Description = description;
                        t.Update();
                        result = true;
                    }
                    catch (Exception ex)
                    {
                        msg = ex.Message;
                    }
                }
                else
                {
                    msg = "You must enter a description.";
                }

                lblMessage.Text = msg;
                

                if (result)
                {
                    grvPhones.EditIndex = -1;
                    BindInfo();
                }       
            }

            return result;
        }

        private void SetIndex(GridView grv, int editIndex)
        {
            grv.EditIndex = editIndex;
            this.BindInfo();
        }

        /// <summary>
        /// Adds onclick to the linkbutton in the gridview.
        /// </summary>
        /// <param name="e"></param>
        /// <param name="deleteWhat">You are about to delete this [deleteWhat]?</param>
        private void RowDataBound(GridViewRowEventArgs e, string deleteWhat)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton l = (LinkButton)e.Row.FindControl("LinkButton1");
                l.Attributes.Add("onclick", string.Format("javascript:return confirm('You are about to delete this {0}?')", deleteWhat.Trim()));
            }
        }
        #endregion
    }
}